/* 该程序使用sigwait对信号SIGUSR1传递给进程的次数计数
 * 要注意信号处理函数不是必须的，因为信号始终是被阻塞的
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>

int main() {
    int signalcount = 0;
    int signo;
    int signum = SIGUSR1;       // 指定为SIGUSR1
    sigset_t sigmask;

    if (sigemptyset(&sigmask) == -1 || 
        sigaddset(&sigmask, signum) == -1 || 
        sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1 ) {
        perror("Failed to block singals before sigwait");
        return -1;
    }

    fprintf(stderr, "This process has ID %ld\n", (long)getpid());

    while (1) {
        // 当sigwait结束后，SIGUSR1会在此被阻塞，因为该函数不会修改进程的信号掩码
        if (sigwait(&sigmask, &signo) == -1) {
            perror("Failed to wait using sigwait");
            return -1;
        }
        signalcount++;
        fprintf(stderr, "Number of signals so far : %d\n", signalcount);

        // if (sigprocmask(SIG_UNBLOCK, &sigmask, NULL) == -1) {
        //     perror("Failed to unblocked the signal");
        //     return -1;
        // }
    }
    fprintf(stderr, "--------------------------------");
    return 0;
}